import { _decorator, Component, director, EditBox, ImageAsset, JsonAsset, Material, Node, Sprite, SpriteFrame, sys } from 'cc';
import Net from 'db://assets/scripts/frame/managers/NetMgr';
import configs from 'db://assets/scripts/Configs';
import oh, { ohPages } from 'db://assets/scripts/ctrl/OhCtrl';
import { aa } from 'db://assets/scripts/frame/FrameCore';
import DecoUtil from './DecoUtils';
import builder from './RoomBuilder';
import { DarkCtrl } from '../ctrl/DarkCtrl';
import { DecoCtrl } from '../ctrl/DecoCtrl';
const { ccclass, property } = _decorator;
declare var window: any

@ccclass('BuildCtrl')
export class BuildCtrl extends Component {
    @property(Node) room: Node = null;
    @property(JsonAsset)
    testJson: JsonAsset = null;
    @property(Material)
    wallMaterial: Material = null;
    @property(Material)
    wallBottomMaterial: Material = null;
    @property(Material)
    wallTopMaterial: Material = null;
    @property(Material)
    floorMaterial: Material = null;
    @property(Material)
    roomMaterial: Material = null;
    @property(Material)
    toiletMat: Material = null;
    @property(Material)
    doorMaterial: Material = null;
    @property
    set scale(v) {
        if (!this._test) {
            const json = this.testJson.json

            json.wallpoints.forEach((w) => {
                w.x = -w.x * builder.scale;
                w.y = w.y * builder.scale;
            });
            json.doors.forEach((door) => {
                door.pos.x *= - builder.scale;
                door.pos.y *= builder.scale;

            });
            json.rooms.forEach((room) => {
                room.pos.x *= -builder.scale;
                room.pos.y *= builder.scale;
            });

        }
        this._test = true;
    }
    get scale() {
        return this._test;
    }

    @property
    set test(v) {
        BuildCtrl.ins = this;

        this.testJsonBuild()
    }
    get test() {
        return false;
    }
    private roomContent: JsonAsset;
    static ins: BuildCtrl;
    onLoad() {
        BuildCtrl.ins = this;
    }
    public _uuid = '2fadc7d4-eee0-46be-bb0f-bd27fc6e6a8c';
    private _test = false;

    start() {
        const json = this.testJson.json

        json.wallpoints.forEach((w) => {
            w.x = -w.x * builder.scale;
            w.y = w.y * builder.scale;
        });
        json.doors.forEach((door) => {
            door.pos.x *= - builder.scale;
            door.pos.y *= builder.scale;

        });
        json.rooms.forEach((room) => {
            room.pos.x *= -builder.scale;
            room.pos.y *= builder.scale;
        });
        window.changeColorMode = function (text) {
            const state = (text == "dark") ? false : true;
            DarkCtrl.ins.setState(state)
        }

        window.showDoc = function (text) {
            console.log("cocos 文档加载成功:" + text)
            DecoCtrl.ins.addBig(text)

        }
        window.showModel = function (text) {
            console.log("cocos 照片加载成功:" + text)
            DecoCtrl.ins.addSmallFromBase64(text)

        }
 
    }
    testJsonBuild() {
        const roomContent = this.testJson.json
        builder.createRoom(roomContent)
    }


    uploadImg() {
        DecoUtil.uploadImageAndGetBase64(async (base64) => {
            if (base64) {
                // 从Base64创建图像资源
                const base64Image = await aa.utils.createTexWithBase64("baee64", base64)
                const sp = new SpriteFrame();
                sp.texture = base64Image;
                // this.testSP && (this.testSP.spriteFrame = sp);
                const roomData = await Net.recognizeDrawing(base64);
                // aa.global.isJson = true;
                try {
                    // 解析字符串为JSON对象
                    let roomContentData: any;
                    if (typeof roomData === 'string') {
                        roomContentData = JSON.parse(roomData);
                    } else {
                        roomContentData = roomData;
                    }
                    console.log('解析房间数据成功:', roomContentData);
                    // 处理墙点数据
                    builder.createRoom(roomContentData);
                    aa.ui.putLoading();

                    console.log('房间3D模型构建完成');
                } catch (error) {

                    console.error('解析或构建房间数据失败:', error);
                }
                // 这里可以处理base64数据，例如展示图片或上传到服务器
            } else {
                aa.ui.putLoading();

                console.log('未获取到图片');
            }
        });
    }

    async testCam() {
        if (sys.platform === sys.Platform.OPENHARMONY) {
            oh.openPage(ohPages.CameraPage);

        } else {
            const res = await Net.sendRequest(configs.serverUrl, { base64: configs.testBase64 })
            console.log("cocos res", res)
            this._uuid = res.uuid || null;
            console.log("cocos uuid", this._uuid)
        }
    }
    async testScan() {
        if (sys.platform === sys.Platform.OPENHARMONY) {
            oh.openPage(ohPages.DocPage);

        }
    }

    async showPic() {
        const prompt = "a white nice chair";
        console.log("cocos start", prompt)
        const res = await Net.fetchGet(configs.serverUrl, { prompt: prompt })
        console.log("cocos build", res)
        const text = await aa.utils.createTexWithBase64("aaadasd", res.base64)
        const spriteFrame = new SpriteFrame();
        spriteFrame.texture = text;
        if (res.uuid) {
            this._uuid = res.uuid;
        }
    }

    async showModel() {
        console.log("cocos start", this._uuid)
        if (!this._uuid) return
        await DecoUtil.loadRemoteModel(this._uuid, 0.25)
    }


    async upload() {
        try {
            // 调用上传方法
            this.roomContent = await this.uploadAndParseJsonFile();

            // 处理解析后的roomContent数据
            console.log('成功获取roomContent:', this.roomContent);

            // TODO: 在这里处理roomContent数据，例如更新UI、生成场景等
            // this.updateRoomUI(this.roomContent);
        } catch (error) {
            console.error('上传或解析JSON文件失败:', error);
            // 可以在这里显示错误提示
        }
    }
    /**
     * 上传JSON文件并解析roomContent
     * @returns 返回一个Promise，解析为roomContent对象
     */
    public uploadAndParseJsonFile(): Promise<any> {
        return new Promise((resolve, reject) => {
            try {
                // 创建文件选择输入框
                const fileInput = document.createElement('input');
                fileInput.type = 'file';
                fileInput.accept = '.json,application/json';
                fileInput.style.display = 'none';
                document.body.appendChild(fileInput);

                // 监听文件选择事件
                fileInput.addEventListener('change', (event) => {
                    // 获取选中的文件
                    const target = event.target as HTMLInputElement;
                    const files = target.files;

                    if (!files || files.length === 0) {
                        document.body.removeChild(fileInput);
                        reject(new Error('没有选择文件'));
                        return;
                    }

                    const file = files[0];
                    console.log('选择的JSON文件:', file.name);

                    // 创建FileReader读取文件内容
                    const reader = new FileReader();

                    reader.onload = (e) => {
                        try {
                            // 解析JSON内容
                            const jsonContent = JSON.parse(e.target.result as string);

                            // 提取roomContent字段
                            if (!jsonContent.roomContent) {
                                throw new Error('文件中不包含roomContent字段');
                            }

                            // 如果roomContent是字符串，尝试解析它
                            let roomContent = jsonContent.roomContent;
                            if (typeof roomContent === 'string') {
                                try {
                                    roomContent = JSON.parse(roomContent);
                                    console.log('已成功解析roomContent字符串为JSON对象');
                                } catch (parseError) {
                                    console.warn('roomContent不是有效的JSON字符串，将作为字符串处理');
                                }
                            }

                            // 移除文件输入框
                            document.body.removeChild(fileInput);

                            // 解析成功，返回roomContent
                            console.log('成功解析JSON文件中的roomContent');
                            resolve(roomContent);
                        } catch (parseError) {
                            document.body.removeChild(fileInput);
                            reject(new Error(`解析JSON文件失败: ${parseError.message}`));
                        }
                    };

                    reader.onerror = () => {
                        document.body.removeChild(fileInput);
                        reject(new Error('读取文件时发生错误'));
                    };

                    // 开始读取文件
                    reader.readAsText(file);
                });

                // 触发文件选择对话框
                fileInput.click();
            } catch (error) {
                reject(new Error(`上传文件过程中发生错误: ${error.message}`));
            }
        });
    }

}

